/**
 * com.monte.persistence.command.MyBatisExecuteCountCommand.java
 * create by FengMy from 2013
 */
package com.monte.persistence.command;

import org.apache.ibatis.mapping.MappedStatement;

import com.monte.mybatis.interceptor.ExecutorInterceptor;
import com.monte.persistence.CommandContext;
import com.monte.persistence.PersistenceCommand;
import com.monte.util.StringUtils;

/**
 * @描述:MyBatis查询结果集数量
 * @author FengMy
 * @since 2013-3-21
 */
public class MyBatisExecuteCountCommand implements PersistenceCommand {
	private String mapper;
	private Object param;
	
	public MyBatisExecuteCountCommand(String mapper, Object param){
		if(StringUtils.isEmpty(mapper)){
			throw new IllegalArgumentException("mybatis mapper could not to be empty");
		}
		this.mapper = mapper;
		this.param = param;
	}

	@Override
	public Integer execute(CommandContext context) {
		MappedStatement state = null;
		try{
			state = context.getSqlSession().getConfiguration().getMappedStatement(mapper+"Count");
		}catch(IllegalArgumentException e){
			//如果没有找到相应的mapper，会抛异常。这里不作处理
		}
		if(state == null){
			return (Integer) context.getSqlSession().selectOne(mapper, new ExecutorInterceptor.CountParameter(param));
		}
		return (Integer) context.getSqlSession().selectOne(mapper + "Count", param);
	}

}
